<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="s" uri="http://www.springframework.org/tags" %>
<html>
<head>
    <style>
        .jw-dialog-hd {
            background: #0066CC;
            color: #fff;
            font-weight: bold;
            font-size: 14px;
            height: 30px;
            padding: 5px 10px 0 10px;
            border-radius: 5px 5px 0 0;
        }

        .jw-dialog-hd td {
            width: 40px
        }
    </style>
    <title>在线下单进出口-按钮</title>
</head>
<body>

<div id="nav-menu" class="ans" style="height: 40px">
    <ul class="ans_left">
        <li class="bnt" showfunction="exportDeclare_customs.do">
            <a href="javascript:submitForm('0');">
                &nbsp;<img src="<s:url value="/cargodecl/images/add.png"/>"/><span>新增</span>
            </a>
        </li>
        <li class="bnt" showfunction="exportDeclare_save.do">
            <a href="javascript:submitForm('1')" onclick='$(window).unbind("beforeunload");'>
                &nbsp;<img src="<s:url value="/cargodecl/images/parse.png"/>"/><span>暂存</span>
            </a>
        </li>
        <!-- <button onclick="savebaseinfo2();">暂存<tton> -->
        <li class="bnt" showfunction="copyHgNewOne.do">
            <a href="javascript:copyHgNewOne()">
                &nbsp;<img src="<s:url value="/cargodecl/images/copy.png"/>"/><span>复制</span>
            </a>
        </li>

        <li class=" bnt" showfunction="report_getHgReportUrl.do"><a href="#" class="xialaguang">
            &nbsp;<img
                src="<s:url value="/cargodecl/images/print.png"/>"/><span>打印&nbsp;&nbsp;</span></a>
            <ul class=" children">
                <a id="printReportA" href="#" style="display:none;" target="_blank"></a>
                <li><a href="javascript:printEntryDeclare(3)">&nbsp;<span style="color:#000;">打印核对单&nbsp;</span></a>
                </li>
                <li><a href="javascript:printEntryDeclare(2)">&nbsp;<span style="color:#000;">打印海关作业联&nbsp;</span></a>
                </li>
                <li><a href="javascript:printEntryDeclare(4)">&nbsp;<span style="color:#000;">打印企业留存联&nbsp;</span></a>
                </li>
                <li><a href="javascript:printEntryDeclare(1)">&nbsp;<span style="color:#000;">打印海关核销联&nbsp;</span></a>
                </li>
                <li><a href="javascript:printEntryDeclare(0)">&nbsp;<span style="color:#000;">打印集装箱&nbsp;</span></a>
                </li>
            </ul>
        </li>
        <script>
            var isEntry = 0;
        </script>
    </ul>
    <script>
        var ajaxFileUpload_eoflag = 1;

        function updateDe() {
            var declaration = $('[name="id"]').val();
            $.ajax({
                       url: "/order/updateDeclaration?id=" + declaration,
                       type: "POST",
                       dataType: "json",
                       success: function () {
                           alert("修改成功");
                       }
                   });
        }
        /**
         *从历史业务数据载入模版，页面导航
         *bizType = [all, booking, trail, declaration]
         */
        function loadBizFromHistory(bizType) {
            //checkData(当前判断条件为checkbox是否被选中)
            //newForm
            //loadData
            if (checkData(bizType)) {
                loadBizFromHistoryOperation(bizType);
            } else {
                jw.confirm("检测到当前页面有未保存的业务数据，是否继续操作，点击确认将覆盖当前数据?", function () {
                    loadBizFromHistoryOperation(bizType);
                }, function () {
                    return;
                });
            }
        }
        function checkData(e) {
            //检查操作
            return true;
        }
        /**
         *从历史业务数据载入模版，真实操作
         *bizType = [all, booking, trail, declaration]
         */
        function loadBizFromHistoryOperation(bizType) {
            if (bizType == "all") {
                jw.dialog({
                              iframe: 'business-businessListForLoadBiz?loadPage=load',
                              width: 815, height: 500
                          });
            } else if (bizType == "book") {
                jw.dialog({
                              iframe: 'business-bookingListForLoadBiz?loadPage=load',
                              width: 815, height: 500
                          });
            } else if (bizType == "trail") {
// 			jw.dialog({ iframe : 'business-trailListForLoadBiz?loadPage=load',
// 				width : 800, height : 430 });
                jw.dialog({
                              iframe: '/business/model-main?type=C',
                              width: 815, height: 500
                          });
            } else if (bizType == "declarate") {
// 			jw.dialog({ iframe : 'business-declarationListForLoadBiz?loadPage=load',
// 				width : 800, height : 300 });
                jw.dialog({
                              iframe: '/business/model-main?type=D',
                              width: 815, height: 500
                          });
            }
        }


    </script>
    <div style="width:800px;;float:left;margin-top:12px">

        <input type="button" id="good_commit" value="提交"
               style="width:40px;float:left;margin-left:5px;padding-right:5px;
                   background-color:#47bf7a;"
               onclick="javascript:submitForm('3')"/>
        <input type="button" id="good_models" value="使用模板"
               style="width:80px;float:left;margin-left:5px;padding-right:5px;
                   background-color:#57bfbf;"
               onclick="loadBizFromHistory('declarate');"/>
        <input type="button" id="good_" value="另存为模板"
               style="width:80px;float:left;margin-left:5px;padding-right:5px;
                   background-color:#14b4c2;"
               onclick="prepareSveAsModel()"/>
        <script type="text/javascript">
            function prepareSveAsModel() {
                jw.dialog({
                              iframe: "<s:url value="/business/prepareSveAsModel"/>",
                              width: 600
                          })
            }
            /**
             * 保存为模板，现由子页面进行调用
             * @param modelName 模板名称
             * @param modelType 模板类型
             */
            function saveAsModel(modelName, modelType, isRecordInfo, businessId) {
                var $inputs = $(".nr-left input[name]");
                var data = {};
                $.each($inputs, function (i, n) {
                    data[n.name] = n.value;
                });
                if (data.length == 0) {
                    alert("保存失败，请刷新页面后重试");
                    return;
                }
                data.modelName = modelName;
                data.modelType = modelType;
                data.isRecordInfo = isRecordInfo;
                data.businessId = businessId;
                alert("这里需要一个loading dialog");
                $.ajax({
                           url: '<s:url value="/business/saveAsModel"/>',
                           data: data,
                           method: 'POST',
                           dataType: 'json',
                           success: function (result) {
                               if (result.rs) {
                                   alert("保存成功");
                               } else {
                                   alert("发生了错误，CODE[" + result.code + "]");
                               }
                           },
                           error: function () {
                               alert("发生了错误，CODE[001]");
                           }
                       });
            }
        </script>
        <input type="button" id="good_1" value="报关资料上传"
               style="width:90px;float:left;margin-left:5px;padding-right:5px;
                   background-color:#f4b713;"
               onclick=""/>
        <div class="uploader " style="width:200px;background-color:#a384e9;float:left;">
            <input type="text" class="filename" style="width:70%" readonly="readonly"/>
            <input type="button" name="" class="button"
                   style="width:29%;background-color:#a384e9;"
                   value="选择文件"/>
            <input type="file" id="hgImportFile" name="file" accept=".xls"
                   onchange="fileOnchange(this)"/>
        </div>
        <input type="button" id="good_importButton" value="报关单excel导入"
               style="width:100px;float:left;margin-left:5px;background-color:#32b1e0;"
               onclick="importBGD()"/>
        <a id="hgImportA" style="border-bottom: 1px solid #2a6496;float:left;"
           <c:if test="${table=='entry'}">href="<s:url value="/order/download/excel_import_declaration"/>"
        </c:if>
           <c:if test="${table=='export'}">href="<s:url value="/order/download/excel_export_declaration"/>"
        </c:if> >下载模板 </a>
        <script type="text/javascript"
                href="<s:url value="cargodecl/js/exportDeclare_customs/exportDeclareModel.js"/>"></script>
    </div>
</div>
</div>

<!-- 报关单excel导入-->
<script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
<script src="http://oss.sheetjs.com/js-xlsx/xlsx.js"></script>
<script>
    var X = XLSX;
    function importBGD() {
        var target = event.target;
        var ov = target.value;
        target.disabled = true;
        target.value = "Loading...";
        var complete = function () {
            target.disabled = false;
            target.value = ov;
        }
        //兼容相对定位
        var xlsImportSpCfg = {
            "报关单新1": {
                sp0: "特殊关系确认:"
            }
        }

        var xlsImportCfg = {
            "报关单新1": {
                收发货人: "A7",
                出口口岸: "F7",
                生产销售单位: "A9",
                运输方式: "F9",
                运输工具名称: "G9",
                监管方式: "F11",
                征免性质: "I11",
                备案号: "L11",
                贸易国: "A13",
                运抵国: "D13",
                指运港: "G13",
                境内货源地: "K13",
                提运单号: "K9",
                许可证号: "A15",
                合同协议号: "A17",
                件数: "D17",
                毛重: "I17",
                净重: "L17",
                备注: "A22",
                成交方式: "D15",
                包装种类: "F17",
                柜号: "A19",
                特殊关系确认: {v: {row: "sp0", col: "C"}},
                价格影响确认: {v: {row: "sp0", col: "F"}},
                支付特许权使用费确认: {v: {row: "sp0", col: "K"}},
                商品数据: {
                    rowStart: "26", rowEnd: "sp0", rowP: 3, datas: {
                        项号: {rowAdd: 0, col: "A"},
                        商品名称: {rowAdd: 0, col: "C"},
                        规格型号: {rowAdd: 2, col: "C"},
                        数量: {rowAdd: 0, col: "F"},
                        单位: {rowAdd: 0, col: "H"},
                        最终目的国: {rowAdd: 0, col: "I"},
                        单价: {rowAdd: 0, col: "K"},
                        总价: {rowAdd: 0, col: "L"},
                        币种: {rowAdd: 0, col: "M"},
                        征免: {rowAdd: 0, col: "N"},
                        商品编号: {rowAdd: 0, col: "B"}
                    }
                }
            }
        }
        handleFile(hgImportFile, xlsImportCfg, xlsImportSpCfg, complete);
    }
    var importContainerListSpeed = 100;//柜号数据导入速度，其实是导入每行柜号前需等待的毫秒数
    function importContainerList() {
        var target = event.target;
        var ov = target.value;
        target.disabled = true;
        target.value = "Loading...";
        var onComplete = function () {
            target.disabled = false;
            target.value = ov;
        }
        var importDataRow = function (rows, posi) {
            var autoConfirmMsg = function () {
                if ($(".messager-window").length > 0) {
                    $(".l-btn-text").click();
                }
            }
            try {
                jzxggselect_123_show.focus();
            } catch (e) {
            }
            try {
                if (posi >= rows.length) {
                    onComplete.apply();
                    if (posi == 0) {
                        alert("识别到柜号数据[0]行。");
                    }
                }
                else {
                    box_jzxh.value = rows[posi]['集装箱号'];
                    autoConfirmMsg.apply();
                    var dtype = rows[posi]['集装箱规格'] == "20" ? "S" : "L";
                    $(".datagrid-row")["S" == dtype ? 0 : 1].click();
                    autoConfirmMsg.apply();
                    box_jzxzz.value = rows[posi]['自重'] == undefined ? "" : rows[posi]['自重'];
                    autoConfirmMsg.apply();
                    box_addButton.click()
                    autoConfirmMsg.apply();
                    setTimeout(function () {
                        importDataRow.call(importDataRow, rows, posi + 1);
                    }, importContainerListSpeed);
                }
            } catch (e) {
                alert("导入失败。" + e);
                onComplete.apply();
            }
        }
        var files = fileForBox.files;
        if (files.length == 0) {
            alert("请选择文件。");
            onComplete.apply();
            return;
        }
        var f = files[0];

        var reader = new FileReader();
        var name = f.name;
        reader.onload = function (e) {
            try {
                var data = e.target.result;
                var wb;
                wb = X.read(data, {type: 'binary'});
                var jarray = X.utils.sheet_to_row_object_array(wb.Sheets[wb.SheetNames[0]]);
                importDataRow(jarray, 0);
                //onComplete.apply();
            } catch (ex) {
                alert("导入失败。" + ex);
                onComplete.apply();
            }
        };
        try {
            reader.readAsBinaryString(f);
        } catch (ex) {
            alert("导入失败。" + ex);
            onComplete.apply();
        }
    }
    function process_wb(workbook, xlsImportCfg, xlsImportSpCfg, onComplete) {
        var r = {};
        for (var attr in xlsImportCfg) {
            var icfg = xlsImportCfg[attr];
            var wbs = workbook.Sheets[attr];
            if (wbs) {
                //初始化相对定位数据
                var sp = {}
                var wsp = xlsImportSpCfg[attr];
                if (wsp) {
                    var fsheet = X.utils.sheet_to_formulae(wbs);
                    fsheet.map(function (cell) {
                        for (var attr in wsp) {
                            if (cell.indexOf(wsp[attr]) != -1) {
                                var celladdr = cell.substr(0, cell.indexOf("="));
                                sp[attr] = {col: celladdr.substr(0, 1), row: celladdr.substr(1)};
                            }
                        }
                    });
                }
                for (var iattr in icfg) {
                    var cell = icfg[iattr];
                    if (!isArray(cell)) {
                        if (typeof cell == 'string') {//普通绝对定位
                            var v = wbs[cell];
                            if (v != undefined && v.v != "") {
                                r[iattr] = v.v;
                            }
                        }
                        else {
                            if (Object.keys(cell).length == 1 && cell['v'] != undefined) {//相对定位直接取值
                                try {
                                    var v = wbs[(sp[cell.v.col] ? sp[cell.v.col].col : cell.v.col)
                                                + (sp[cell.v.row] ? sp[cell.v.row].row
                                            : cell.v.row)];
                                } catch (ex) {
                                }
                                if (v && v.v != "") {
                                    r[iattr] = v.v;
                                }
                            }
                            else {//相对定位数组对象取值
                                if (cell['rowStart'] != undefined) {//行拓展
                                    try {
                                        var rowEnd = sp[cell.rowEnd].row - 0;
                                    } catch (ex) {
                                    }
                                    if (rowEnd) {
                                        var rdatas = [];
                                        var dataCfg = cell.datas;
                                        for (var di = (cell.rowStart - 0); di < rowEnd;
                                             di += cell.rowP) {
                                            var d = {};
                                            for (var dattr in dataCfg) {
                                                try {
                                                    var v = wbs[dataCfg[dattr].col + (di
                                                                + dataCfg[dattr].rowAdd)];
                                                } catch (ex) {
                                                }
                                                if (v && v.v != "") {
                                                    d[dattr] = v.v;
                                                }
                                            }
                                            if (Object.keys(d).length > 0) {
                                                rdatas.push(d);
                                            }
                                        }
                                        r[iattr] = rdatas;
                                    }
                                }
                                else {//列拓展

                                }
                            }
                        }
                    }
                }
            }
        }
        if (Object.keys(r).length > 0) {
            console.log(r);
            $.get("getExcelModel?dt=E&d=" + encodeURIComponent(JSON.stringify(r)),
                  function (result) {
                      //console.log(result);
                      onComplete.apply();
                  });
        } else {
            alert("模板内容识别失败。");
            onComplete.apply();
        }
    }
    function isArray(o) {
        return Object.prototype.toString.call(o) === '[object Array]';
    }
    function handleFile(fileInput, cfg, xlsImportSpCfg, onComplete) {
        var files = fileInput.files;
        if (files.length == 0) {
            alert("请选择文件。");
            onComplete.apply();
            return;
        }
        var f = files[0];

        var reader = new FileReader();
        var name = f.name;
        reader.onload = function (e) {
            try {
                var data = e.target.result;
                var wb;
                wb = X.read(data, {type: 'binary'});
                process_wb(wb, cfg, xlsImportSpCfg, onComplete);
            } catch (ex) {
                alert("导入失败。" + ex);
                onComplete.apply();
            }

        };
        try {
            reader.readAsBinaryString(f);
        } catch (ex) {
            alert("导入失败。" + ex);
            onComplete.apply();
        }

    }
</script>
</body>
</html>
